import type { Feature, LineString, GeoJsonProperties } from 'geojson'
import type { MapFeatures, SymbolFeature } from '@/map'
import { highLightProperties } from '@/map/highlights'
import { getEntityMap } from '../base'
import { type Waypoint } from '../waypoint'
import { highLightAirportFeature, type Airport } from '../airport'
import type { Routing } from './types'

export function routing2Feature<G extends GeoJsonProperties>(
  lst: Routing,
  properties: G
): Feature<LineString, G> {
  const wpts = getEntityMap<Waypoint>('Waypoint')
  return _routing2Feature(lst, properties, wpts)
}

function _routing2Feature<G extends GeoJsonProperties>(
  lst: Routing,
  properties: G,
  wpts: Record<string, Waypoint>,
  apts: Record<string, Airport> | null = null
): Feature<LineString, G> {
  const coordinates = lst.waypointList.map((wId) => {
    const loc = wpts[wId].location
    return [loc.lng, loc.lat]
  })
  if (apts) {
    if (lst.departureAirport) {
      const apt = apts[lst.departureAirport]
      coordinates.splice(0, 0, [apt.location.lng, apt.location.lat])
    }
    if (lst.arrivalAirport) {
      const apt = apts[lst.arrivalAirport]
      coordinates.push([apt.location.lng, apt.location.lat])
    }
  }
  return {
    type: 'Feature',
    geometry: {
      type: 'LineString',
      coordinates
    },
    properties
  }
}

export function highLightRoutingFeatures(r: Routing): MapFeatures {
  const wpts = getEntityMap<Waypoint>('Waypoint')
  const apts = getEntityMap<Airport>('Airport')
  const symbol: SymbolFeature[] = []
  if (r.departureAirport) {
    const apt = apts[r.departureAirport]
    symbol.push(highLightAirportFeature(apt))
  }

  const symbolProperty = highLightProperties.symbol.primary('')
  for (const wptId of r.waypointList) {
    const wpt = wpts[wptId]
    const { lng, lat } = wpt.location
    const f: SymbolFeature = {
      type: 'Feature',
      geometry: {
        type: 'Point',
        coordinates: [lng, lat]
      },
      properties: symbolProperty
    }
    symbol.push(f)
    // symbol.push(highLightWaypointFeature(wpt))
  }
  if (r.arrivalAirport) {
    const apt = apts[r.arrivalAirport]
    symbol.push(highLightAirportFeature(apt))
  }
  const p = highLightProperties.line.primary
  const line = [_routing2Feature(r, p, wpts, apts)]
  return { symbol, line }
}
